package com.iexbuy.ihg.ui.fragment;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.navisdk.ui.routeguide.subview.L;
import com.baidu.navisdk.util.common.StringUtils;
import com.iexbuy.ihg.App;
import com.iexbuy.ihg.R;
import com.iexbuy.ihg.common.CommUtil;
import com.iexbuy.ihg.entity.AddressObject;
import com.iexbuy.ihg.entity.AddressObjectResponse;
import com.iexbuy.ihg.entity.Shop;
import com.iexbuy.ihg.entity.ShopItemDetailObject;
import com.iexbuy.ihg.entity.ShopItemListObject;
import com.iexbuy.ihg.entity.XiaoFeiOrderConfirmObject;
import com.iexbuy.ihg.net.ServiceHelper;
import com.iexbuy.ihg.utils.JsonUtils;
import com.iexbuy.ihg.utils.StringUtil;
import com.iexbuy.ihg.utils.ToastUtils;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class OrderConfirmFragment extends BaseFragment {
	
	private static OrderConfirmFragment homeFragmentInstent;
	private View rootView;

	@ViewInject(R.id.msgListLayout)
	private PullToRefreshLayout msgListRefreshLayout;
	@ViewInject(R.id.listView)
	private ListView listView;

	private LinearLayout listHeaderView;
	@ViewInject(R.id.productName)
	private TextView productName;
	@ViewInject(R.id.price)
	private TextView price;
	@ViewInject(R.id.buyNumber)
	private EditText buyNumber;
	@ViewInject(R.id.expressPrice)
	private TextView expressPrice;
	@ViewInject(R.id.totalPayAmount)
	private TextView totalPayAmount;
	@ViewInject(R.id.priceLabel)
	private TextView priceLabel;
	@ViewInject(R.id.discountTips)
	private TextView discountTips;
	@ViewInject(R.id.discountCash)
	private TextView discountCash;
	@ViewInject(R.id.obtainGold)
	private TextView obtainGold;
	@ViewInject(R.id.addressTips)
	private TextView addressTips;
	@ViewInject(R.id.addressInfoLayout)
	private LinearLayout addressInfoLayout;
	@ViewInject(R.id.addressContacter)
	private TextView addressContacter;
	@ViewInject(R.id.addressMobile)
	private TextView addressMobile;
	@ViewInject(R.id.address)
	private TextView address;

	private static ShopItemDetailObject shopItemDetailObject;
	private XiaoFeiOrderConfirmObject xiaoFeiOrderConfirmObject;

	private List<AddressObject> addressObjects = new ArrayList<AddressObject>();
	private AddressObject selectAddress;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		homeFragmentInstent = this;
	}

	@Override
	protected View _onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_order_confirm, container, false);
		ViewUtils.inject(this, rootView);
		initView(rootView);
		return rootView;
	}

	private void initView(View rootView) {
		if ("1".equalsIgnoreCase(shopItemDetailObject.getGoodsType())) {
			//面对面支付
			mBaseActivity.setTitle(getResources().getString(R.string.title_direct_pay_order_confirm));
		} else {
			mBaseActivity.setTitle(getResources().getString(R.string.title_order_confirm));
		}

		mBaseActivity.setTitleLayoutVisibility(true);
		mBaseActivity.setHomeActivity(false);

		initOrderlView();
	}

	private void initOrderlView() {
		if (shopItemDetailObject == null) return;
		productName.setText(shopItemDetailObject.getItemName());
		if ("1".equalsIgnoreCase(shopItemDetailObject.getGoodsType())) {//根据商品类型显示
			showDirectPayView();
		} else {
			showGoodsView();
		}

		price.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
			@Override
			public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
			@Override
			public void afterTextChanged(Editable editable) {
				calculatTotalAmount();
			}
		});
		//输入监听
		buyNumber.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
			}

			@Override
			public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
			}

			@Override
			public void afterTextChanged(Editable editable) {
				calculatTotalAmount();
			}
		});
		calculatTotalAmount();

		initDefaultAddress();
	}

	//计算价格
	private void calculatTotalAmount() {

		String priceValue = price.getText().toString();
		String number = buyNumber.getText().toString();
		String expressValue = expressPrice.getText().toString();
		if(StringUtils.isNotEmpty(priceValue) && StringUtils.isNotEmpty(number)) {
			priceValue = priceValue.replaceAll("元", "");
			expressValue = expressValue.replaceAll("元", "");
			String totalAmount = "0";
			String discountCashValue = "0";
			String obtainGoldCoin = "0";
			try {
				//计算总额
				if ("1".equalsIgnoreCase(shopItemDetailObject.getGoodsType())) {//如果是直接支付，要先乘一个折扣
					totalAmount = new BigDecimal(priceValue).multiply(new BigDecimal(shopItemDetailObject.getDiscount()).divide(new BigDecimal("100"))).setScale(2, BigDecimal.ROUND_HALF_UP).add(new BigDecimal(expressValue)).toString();
					discountCashValue = new BigDecimal(priceValue).subtract(new BigDecimal(totalAmount)).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
				} else {
					totalAmount = new BigDecimal(priceValue).multiply(new BigDecimal(number)).setScale(2, BigDecimal.ROUND_HALF_UP).add(new BigDecimal(expressValue)).toString();
					discountCashValue = new BigDecimal(shopItemDetailObject.getOldPrice()).multiply(new BigDecimal(number)).setScale(2, BigDecimal.ROUND_HALF_UP).add(new BigDecimal(expressValue)).subtract(new BigDecimal(totalAmount)).toString();
				}
			} catch (Exception e) {
				ToastUtils.toast(mBaseActivity, "请输入正确的购买数量。");
			}
			totalPayAmount.setText(totalAmount+"元");
			discountCash.setText(discountCashValue+"元");
			obtainGold.setText(CommUtil.calculatCoinFromCash(totalAmount, shopItemDetailObject.getShop().getShareRate()) + "个");
//			obtainGold.setText(CommUtil.calculatCoinFromCash(totalAmount, "2.4") + "个");
		} else {
			totalPayAmount.setText("0.00元");
			discountCash.setText("0.00元");
			obtainGold.setText("0个");
		}
	}

	private void showGoodsView() {
		priceLabel.setText("单价");
		price.setText(shopItemDetailObject.getNewPrice());
		price.setEnabled(false);
		buyNumber.setText("1");//默认是1
		expressPrice.setText(String.valueOf(shopItemDetailObject.getExpressPrice()) + "元");

		rootView.findViewById(R.id.discountTipsLayout).setVisibility(View.GONE);
		rootView.findViewById(R.id.buyNumberLayout).setVisibility(View.VISIBLE);
		rootView.findViewById(R.id.expressPriceLayout).setVisibility(View.VISIBLE);
		rootView.findViewById(R.id.addressLayout).setVisibility(View.VISIBLE);
	}

	private void showDirectPayView() {
		priceLabel.setText("买单价");
		price.setText("");
		price.setHint("请输入买单价格");
		buyNumber.setText("1");//默认是1
		discountTips.setText("特享商家优惠" + shopItemDetailObject.getDiscount() + "折");

		rootView.findViewById(R.id.discountTipsLayout).setVisibility(View.VISIBLE);
		rootView.findViewById(R.id.buyNumberLayout).setVisibility(View.GONE);
		rootView.findViewById(R.id.expressPriceLayout).setVisibility(View.GONE);
		rootView.findViewById(R.id.addressLayout).setVisibility(View.GONE);
	}

	private void initDefaultAddress() {
		HashMap<String, String> paramMap = new HashMap<String, String>();
		ServiceHelper.send(mBaseActivity, ServiceHelper.GET_MY_ADDRESS, paramMap,
				new RequestCallBack<String>() {
					@Override
					public void onStart() {
					}

					@Override
					public void onCancelled() {
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						AddressObjectResponse rep = JsonUtils.parseJsonStrToObject(responseInfo.result, AddressObjectResponse.class);
						if (rep.getBody() != null) {
							for (AddressObject addressObject : rep.getBody()) {
								if ("1".equalsIgnoreCase(addressObject.getDefAddr())) {
									selectAddress = addressObject;
									initAddressView();
									break;
								}
							}
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
					}
				});
	}

	private void initAddressView() {
		if (selectAddress != null) {
			addressInfoLayout.setVisibility(View.VISIBLE);
			addressTips.setVisibility(View.GONE);

			addressContacter.setText("收件人："+selectAddress.getReceiver());
			addressMobile.setText("电话："+selectAddress.getMobile());
			address.setText("地址："+selectAddress.getAddress());
		} else {
			addressInfoLayout.setVisibility(View.GONE);
			addressTips.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 提交订单
	 * @param view
	 */
	@OnClick(R.id.submitOrderBtn)
	public void onSubmitOrderBtnClick(View view) {
		if (StringUtils.isEmpty(price.getText().toString())) {
			ToastUtils.toast(mBaseActivity, "请输入支付价格。");
			price.requestFocus();
			return;
		}
		if (StringUtils.isEmpty(buyNumber.getText().toString())) {
			ToastUtils.toast(mBaseActivity, "请输入购买数量。");
			buyNumber.requestFocus();
			return;
		}

		submitOrder();
	}

	private void submitOrder() {
		HashMap<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("goodsId", shopItemDetailObject.getItemId());
		paramMap.put("requestNumber", buyNumber.getText().toString());
		paramMap.put("phone", "");
		if (selectAddress != null) {
			paramMap.put("addrId", selectAddress.getAddressId());
		}
		paramMap.put("couponId", "");
		ServiceHelper.send(mBaseActivity, ServiceHelper.SUBMIT_DEAL, paramMap,
				new RequestCallBack<String>() {
					@Override
					public void onStart() {
						mBaseActivity.showDialog("提交中...");
					}

					@Override
					public void onCancelled() {
						mBaseActivity.closeDialog();
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						mBaseActivity.closeDialog();
						xiaoFeiOrderConfirmObject = JsonUtils.parseJsonStrToObject(JsonUtils.getJsonSubStringByKey(responseInfo.result, "body"), XiaoFeiOrderConfirmObject.class);
						xiaoFeiOrderConfirmObject.setPrice(shopItemDetailObject.getNewPrice());

						CommUtil.showAlert(mBaseActivity, "下单成功", "购买商品成功，即将转到支付界面，本次支付可获得金币" + obtainGold.getText().toString(), new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialogInterface, int i) {
								PayConfirmFragment.setRequestNo(Integer.valueOf(buyNumber.getText().toString()));
								if ("1".equalsIgnoreCase(shopItemDetailObject.getGoodsType())) {
									xiaoFeiOrderConfirmObject.setPrice(price.getText().toString());
									xiaoFeiOrderConfirmObject.setPayMoney(totalPayAmount.getText().toString().replaceAll("元", ""));
									xiaoFeiOrderConfirmObject.setObtainCoin(obtainGold.getText().toString());
								}
								PayConfirmFragment.setXiaoFeiOrderConfirmObject(xiaoFeiOrderConfirmObject);
								CommUtil.openSingleFragmentActivity(mBaseActivity, PayConfirmFragment.class);
								mBaseActivity.finish();
							}
						});
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						mBaseActivity.closeDialog();
						ToastUtils.toast(mBaseActivity, msg);
					}
				});
	}

	@OnClick(R.id.addressLayout)
	public void addressLayoutClick(View view) {
		WeDeAddresssFragment.setOnSelectedListener(new WeDeAddresssFragment.OnSelectedListener() {
			@Override
			public void onSelected(AddressObject addressObject) {
				selectAddress = addressObject;
				initAddressView();
			}
		});
		CommUtil.openSingleFragmentActivity(mBaseActivity, WeDeAddresssFragment.class);
	}

	public static void setShopItemDetailObject(ShopItemDetailObject shopItemDetailObject) {
		OrderConfirmFragment.shopItemDetailObject = shopItemDetailObject;
	}

	/**
	 * @return the homeFragmentInstent
	 */
	public static OrderConfirmFragment getHomeFragmentInstent() {
		return homeFragmentInstent;
	}

}
